package operation

import (
	"context"
	"github.com/gogf/gf/v2/container/garray"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/encoding/gjson"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gconv"
	"hotgo/internal/consts"
	"hotgo/internal/library/contexts"
	"hotgo/internal/model/input/adminin"
	"hotgo/internal/service"

	"hotgo/api/api/operation/v1"
)

// RedPacket 领取新人红包
func (c *ControllerV1) RedPacket(ctx context.Context, req *v1.RedPacketReq) (res *v1.RedPacketRes, err error) {

	user, err := service.AdminMember().LoginMemberInfo(ctx)
	if err != nil {
		return
	}

	// 新人积分设置
	if garray.NewStrArrayFrom(gconv.Strings(user.Label.Array())).ContainsI(consts.AdminMemberLabelGuest) {
		err = g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) (err error) {

			// 获取新人积分设置
			config, err := service.SysConfig().GetPoints(ctx)
			if err != nil {
				return
			}

			// 领取积分
			if _, err = service.AdminCreditsLog().SaveIntegral(ctx, &adminin.CreditsLogSaveIntegralInp{
				MemberId:    user.Id,
				AppId:       contexts.GetModule(ctx),
				AddonsName:  contexts.GetAddonName(ctx),
				CreditGroup: consts.CreditGroupIncr,
				Num:         config.NewMemberPoints,
				Remark:      "领取新人有礼红包",
			}); err != nil {
				return gerror.New("领取失败,请稍后重试")
			}

			// 更新用户标签
			if err = service.AdminMember().UpdateInfo(ctx, &adminin.MemberUpdateInfoInp{
				ID:    user.Id,
				Label: gjson.New([]string{consts.AdminMemberLabelNewbie}),
			}); err != nil {
				return gerror.New("领取失败,请稍后重试")
			}
			return
		})
	} else {
		return nil, gerror.New("非新人无法领取")
	}

	return
}

// ProductNewList 新人商品列表
func (c *ControllerV1) ProductNewList(ctx context.Context, req *v1.ProductNewListReq) (res *v1.ProductNewListRes, err error) {
	list, err := service.ApiOperation().ProductNewList(ctx)
	if err != nil {
		return
	}
	res = new(v1.ProductNewListRes)
	res.List = list
	return
}

// ExchangeHistory 新人商品兑换记录
func (c *ControllerV1) ExchangeHistory(ctx context.Context, req *v1.ExchangeHistoryReq) (res *v1.ExchangeHistoryRes, err error) {
	list, err := service.ApiOperation().ProductNewExchangeHistory(ctx)
	if err != nil {
		return
	}
	res = new(v1.ExchangeHistoryRes)
	res.List = list
	return
}

// ProductGroupExchangeHistory 团购商品兑换记录
func (c *ControllerV1) ProductGroupExchangeHistory(ctx context.Context, req *v1.ProductGroupExchangeHistoryReq) (res *v1.ProductGroupExchangeHistoryRes, err error) {
	list, err := service.ApiOperation().ProductGroupExchangeHistory(ctx)
	if err != nil {
		return
	}
	res = new(v1.ProductGroupExchangeHistoryRes)
	res.List = list
	return
}

// MemberCard 查询会员卡列表
func (c *ControllerV1) MemberCard(ctx context.Context, req *v1.MemberCardReq) (res *v1.MemberCardRes, err error) {
	list, err := service.ApiOperation().MemberCard(ctx, req.Show)
	if err != nil {
		return
	}
	res = new(v1.MemberCardRes)
	res.List = list
	return
}
